package cn.sumpu.app.guoguojie.biz.impl;

import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import cn.sumpu.app.guoguojie.biz.AlbumBiz;
import cn.sumpu.app.guoguojie.biz.ImageBiz;
import cn.sumpu.app.guoguojie.constant.PictureType;
import cn.sumpu.app.guoguojie.domain.Member;
import cn.sumpu.app.guoguojie.domain.OnLineUserListener;
import cn.sumpu.app.guoguojie.exception.AppBusinessException;
import cn.sumpu.app.guoguojie.util.Common;
import cn.sumpu.app.guoguojie.util.ImageWeb;
import cn.sumpu.app.guoguojie.util.PictureUrl;
import cn.sumpu.app.guoguojie.util.ScaleImage;

public class AlbumBizImpl implements AlbumBiz {

	@Autowired
	private ImageBiz imageBiz;

	private String imageServer;

	private String imageDir;

	public String getImageDir() {
		return imageDir;
	}

	public void setImageDir(String imageDir) {
		this.imageDir = imageDir;
	}

	public String getImageServer() {
		return imageServer;
	}

	public void setImageServer(String imageServer) {
		this.imageServer = imageServer;
	}

	@Transactional(rollbackForClassName = { "cn.sumpu.app.guoguojie.exception.AppBusinessException" }, timeout = 10)
	public void uploadPhoto(HttpServletRequest request)
			throws AppBusinessException {
		Member member = (Member) request.getSession().getAttribute("member");

		MultipartHttpServletRequest re = (MultipartHttpServletRequest) request;
		Map<String, MultipartFile> map = re.getFileMap();
		List<MultipartFile> fileList = new ArrayList<MultipartFile>();
		for (Object obj : map.values()) {
			MultipartFile file = (MultipartFile) obj;
			fileList.add(file);
		}

		if (fileList.size() > 0) {

			try {
				int feedImgId = 1;
				for (int i = 0; i < fileList.size(); i++) {
					MultipartFile fj = fileList.get(i);
					String fn = fj.getOriginalFilename();
					if (null != fn && fn.length() > 0) {
						String family = member.getFamily();
						String formateDate = Common.getFormatDate(new Date());

						InputStream buffin = new ByteArrayInputStream(
								fj.getBytes());
						BufferedImage bi = ImageIO.read(buffin);
						if (bi != null) {
							String imageType = fn
									.substring(fn.lastIndexOf(".") + 1);
							String uuid = UUID.randomUUID().toString();
							String savePathServer = "pic/"
									+ PictureType.ALBUM.getValue() + "/"
									+ formateDate + "/" + family;
							int pWidth = bi.getWidth();
							int pHeight = bi.getHeight();
							double zoom = (double) Common.THUMB_WIDTH / pWidth;
							double zoom2 = (double) Common.THUMB_HEIGHT
									/ pHeight;
							if (zoom2 < zoom) {
								zoom = zoom2;
							}
							int tagWidth = (int) (zoom * pWidth);
							int tagHeight = (int) (zoom * pHeight);
							String serverUrl = imageServer
									+ "receiveImage.htm";

							byte[] formatBtye = ScaleImage.saveImageAsJpg(bi,
									tagWidth, tagHeight);
							imageBiz.requestSaveImage(serverUrl,
									savePathServer, uuid + "_thumb."
											+ imageType, formatBtye);
							// 保存原始图片,如果原始图片大于规定的大小则将图片缩略成规定的大小
							double zoom3 = (double) Common.ORG_WIDTH / pWidth;
							if (zoom3 < 1) {
								int orgWidth = (int) (zoom3 * pWidth);
								int orgHeight = (int) (zoom3 * pHeight);

								byte[] orgBtye = ScaleImage.saveImageAsJpg(bi,
										orgWidth, orgHeight);
								imageBiz.requestSaveImage(serverUrl,
										savePathServer, uuid + "." + imageType,
										orgBtye);
							} else {
								imageBiz.requestSaveImage(serverUrl,
										savePathServer, uuid + "." + imageType,
										fj.getBytes());
							}

							feedImgId++;
						}

					}
				}
				String ownerType = request.getParameter("ownerType");
				request.setAttribute("ownerType", ownerType);
				String owner = request.getParameter("owner");
				request.setAttribute("owner", owner);
			} catch (Exception e) {
				e.printStackTrace();
				throw new AppBusinessException("upload fail", e);
			}

		}

	}

	@Override
	public PictureUrl uploadImage(HttpServletRequest request, String picType,
			boolean isZip) throws AppBusinessException { 
		Member member = OnLineUserListener.getSessionMember(request); 
		PictureUrl picUrl = new PictureUrl();

		try { 
			MultipartHttpServletRequest re = (MultipartHttpServletRequest) request;

			Map<String, MultipartFile> map = re.getFileMap();
			List<MultipartFile> fileList = new ArrayList<MultipartFile>();
			for (Object obj : map.values()) {
				MultipartFile file = (MultipartFile) obj;
				fileList.add(file);
			}
			if (fileList.size() > 0) {
				for (int i = 0; i < fileList.size(); i++) {
					MultipartFile fj = fileList.get(i);
					String fn = fj.getOriginalFilename();
					if (null != fn && fn.length() > 0) {
						picUrl.setFileOrgName(fn);
						String formateDate = Common.getFormatDate(new Date());

						InputStream buffin = new ByteArrayInputStream(fj.getBytes());
						BufferedImage bi = ImageIO.read(buffin);
						if (bi != null) {
							// 文件类型
							String imageType = fn.substring(fn.lastIndexOf(".") + 1);  
							String uuid = UUID.randomUUID().toString(); 
							String savePathServer = "";
							if ("background".equals(picType) || "rush".equals(picType) || "stroll".equals(picType) ||"product".equals(picType)||"discuss".equals(picType)) {
								if("temp".equals(request.getParameter("contentId"))){
								    savePathServer = "pic/temp";
								}else{
								    savePathServer = "pic/" + picType + "/"
                                    + formateDate + "/"
                                    + request.getParameter("contentId");
								}
							} else {
								savePathServer = "pic/" + picType + "/"
										+ formateDate + "/"
										+ member.getIdentifier();
							}
							int pWidth = bi.getWidth();
							int pHeight = bi.getHeight();

							String serverUrl = imageServer + "receiveImage.htm";
							
							
							
							
							double zoom3 = (double) Common.ORG_WIDTH / pWidth;
							if (picType.equals(PictureType.DOING.getValue())) {
								zoom3 = (double) Common.ORG_WIDTH_DOING / pWidth;
							} else if (picType.equals(PictureType.ACTIVITY .getValue())) {
								zoom3 = (double) Common.ORG_WIDTH_ACTIVITY / pWidth;
							} else if (picType.equals(PictureType.CROWD.getValue())) {
								zoom3 = (double) Common.ORG_WIDTH_CROWD / pWidth;
							} else if (picType.equals(PictureType.COMPANY .getValue())) {
								zoom3 = (double) Common.ORG_WIDTH_COMPANY / pWidth;
							} else if (picType.equals(PictureType.COMMUNITY .getValue())) {
								zoom3 = (double) Common.ORG_WIDTH_COMMUNITY / pWidth;
							} else if (picType.equals(PictureType.PRODUCT.getValue())) {
								zoom3 = (double) Common.ORG_WIDTH_PRODUCT / pWidth;
							}

							// 保存原始图片
							if (zoom3 < 1) {
								int orgWidth = (int) (zoom3 * pWidth);
								int orgHeight = (int) (zoom3 * pHeight);
								
								imageBiz.cutImage(fj.getBytes(), orgWidth, orgHeight, savePathServer, uuid + ".jpg");
								imageType = "jpg";
							}else{
								imageBiz.requestSaveImage(serverUrl,savePathServer, uuid + "." + imageType,fj.getBytes());
							}

							picUrl.setOriginal(savePathServer + "/" + uuid + "." + imageType);
							picUrl.setImageServer(imageServer);
							picUrl.setPictureUrl(savePathServer + "/" + uuid + "." + imageType);
							picUrl.setUrl(imageServer + savePathServer + "/" + uuid + "." + imageType);
							
							// 保存缩略图	
							if (isZip) {
								double zoomW = (double)Common.THUMB_WIDTH_150 / pWidth; 
								double zoomH = (double)Common.THUMB_HEIGHT_160 / pHeight;
								if(zoomW < zoomH){
									//150
									imageBiz.cutImage(fj.getBytes(), Common.THUMB_WIDTH_150, -1, savePathServer, uuid + "_thumb.jpg" + "_150x160.jpg");
								}else{
									//150
									imageBiz.cutImage(fj.getBytes(), -1,Common.THUMB_HEIGHT_160, savePathServer, uuid + "_thumb.jpg" + "_150x160.jpg");
								}
								
								
								//100x100
								imageBiz.cutImage(fj.getBytes(), Common.THUMB_WIDTH_100, Common.THUMB_HEIGHT_100, savePathServer, uuid + "_thumb.jpg" + "_100x100.jpg");
								
								//200x200
								imageBiz.cutImage(fj.getBytes(), Common.THUMB_WIDTH_200, Common.THUMB_HEIGHT_200, savePathServer, uuid + "_thumb.jpg" + "_200x200.jpg");
								
								
								//200xXXX
								ImageWeb iw = imageBiz.cutImage(fj.getBytes(), Common.THUMB_WIDTH_200, -1, savePathServer, uuid + "_thumb.jpg" + "_200xXXX.jpg");
								picUrl.setWidth200xxx(iw.getWidth());
								picUrl.setHeight200xxx(iw.getHeight());
								
								//320xXXX
								imageBiz.cutImage(fj.getBytes(), Common.THUMB_WIDTH_320, -1, savePathServer, uuid + "_thumb.jpg" + "_320xXXX.jpg");
								
								//468xXXX
								imageBiz.cutImage(fj.getBytes(), Common.ORG_WIDTH_DOING, -1, savePathServer, uuid + "_thumb.jpg" + "_468xXXX.jpg");
								
								picUrl.setThumbnail(savePathServer + "/" + uuid + "_thumb.jpg");

							}

							
							return picUrl;
						}
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new AppBusinessException("upload fail", e);
		}
		return null;
	}

	// 后台的上传图片的方法
	@Override
	public PictureUrl uploadPicture(String pictureUrl)
			throws AppBusinessException {
		try {
			PictureUrl picture = new PictureUrl();  
			String uuid = UUID.randomUUID().toString();
			File f = new File(imageDir + "/pic/background/"
					+ Common.getFormatDate(new Date()));
			if (!f.exists()) {
				f.mkdirs();
			}
			String toPath = imageDir + "/pic/background/"
					+ Common.getFormatDate(new Date()) + "/" + uuid + ".jpg";
			URL uu = new URL(pictureUrl);
			BufferedImage bi = ImageIO.read(uu.openStream());
			File file = new File(toPath);
			ImageIO.write(bi, "JPG", file);
			picture.setImageServer(imageServer);
			picture.setPictureUrl("pic/background/"
					+ Common.getFormatDate(new Date()) + "/" + uuid + ".jpg");
			return picture;
		} catch (Exception e) {
			e.printStackTrace();
			return new PictureUrl();
		}
	}
	
}
